package com.cskaoyan.service.impl;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.MarketUser;
import com.cskaoyan.bean.zhangsenqi.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.service.CartService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author zhangsenqi
 * @Description
 * @Create 2022-06-29 14:08
 * @Version
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    MarketCartMapper marketCartMapper;
    @Autowired
    MarketGoodsMapper marketGoodsMapper;
    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;
    @Autowired
    MarketAddressMapper marketAddressMapper;
    @Autowired
    MarketSystemMapper marketSystemMapper;
    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;
    @Autowired
    MarketCouponMapper marketCouponMapper;
    @Autowired
    MarketGrouponRulesMapper marketGrouponRulesMapper;

    @Override
    public CartData index() {
        // 获取用户 id
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection principals = subject.getPrincipals();

        // 未登录
        if (principals == null) {
            return null;
        }
        MarketUser primaryPrincipal = (MarketUser) principals.getPrimaryPrincipal();
        Integer userId = primaryPrincipal.getId();

        // 从数据库中获取 cartList
        MarketCartExample cartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        criteria.andUserIdEqualTo(userId);
        List<MarketCart> cartList = marketCartMapper.selectByExample(cartExample);

        CartTotal cartTotal = getCartTotal(userId);

        CartData cartData = new CartData();
        cartData.setCartList(cartList);
        cartData.setCartTotal(cartTotal);

        return cartData;
    }

    /**
     * getCartTotal 用于显示购物车信息
     *
     * @return cartTotal
     */
    private CartTotal getCartTotal(Integer userId) {
        // goodsCount
        Integer goodsCount = marketCartMapper.goodsCount(userId);

        // checkedGoodsCount
        Integer checkedGoodsCount = marketCartMapper.checkedGoodsCount(userId);

        // goodsAmount
        Double goodsAmount = marketCartMapper.goodsAmount(userId);

        // checkedGoodsAmount
        Double checkedGoodsAmount = marketCartMapper.checkedGoodsAmount(userId);

        // 对 cartTotal 进行赋值
        CartTotal cartTotal = new CartTotal();
        cartTotal.setGoodsCount(goodsCount == null ? 0 : goodsCount);
        cartTotal.setCheckedGoodsCount(checkedGoodsCount == null ? 0 : checkedGoodsCount);
        cartTotal.setGoodsAmount(goodsAmount == null ? 0 : goodsAmount);
        cartTotal.setCheckedGoodsAmount(checkedGoodsAmount == null ? 0 : checkedGoodsAmount);
        return cartTotal;
    }

    @Override
    public CartData checked(CheckedParam checkedParam) {

        // 获取用户 id
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection principals = subject.getPrincipals();

        // 未登录
        if (principals == null) {
            return null;
        }
        MarketUser primaryPrincipal = (MarketUser) principals.getPrimaryPrincipal();
        Integer userId = primaryPrincipal.getId();

        // 修改 当前用户的 购物车中的选中信息
        MarketCartExample example = new MarketCartExample();
        MarketCartExample.Criteria criteria = example.createCriteria();
        criteria.andProductIdIn(Arrays.asList(checkedParam.getProductIds()));
        criteria.andUserIdEqualTo(userId);

        MarketCart marketCart = new MarketCart();
        marketCart.setChecked(checkedParam.getIsChecked() == 1 ? true : false);
        marketCart.setUpdateTime(new Date());

        marketCartMapper.updateByExampleSelective(marketCart, example);

        // 回显
        MarketCartExample cartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria2 = cartExample.createCriteria();
        criteria2.andDeletedEqualTo(false);
        criteria2.andUserIdEqualTo(userId);

        List<MarketCart> cartList = marketCartMapper.selectByExample(cartExample);

        // goodsCount
        CartTotal cartTotal = getCartTotal(userId);

        CartData cartData = new CartData();
        cartData.setCartList(cartList);
        cartData.setCartTotal(cartTotal);

        return cartData;
    }

    @Override
    public long add(MarketCart marketCart) {
        // 获取用户 id
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection principals = subject.getPrincipals();

        // 未登录
        if (principals == null) {
            return -1;
        }
        MarketUser primaryPrincipal = (MarketUser) principals.getPrimaryPrincipal();
        Integer userId = primaryPrincipal.getId();
        // 查询购物车中有没有该商品
        MarketCartExample cartExample = new MarketCartExample();
        cartExample.createCriteria().andDeletedEqualTo(false).andGoodsIdEqualTo(marketCart.getGoodsId()).andUserIdEqualTo(userId);

        List<MarketCart> marketCarts = marketCartMapper.selectByExample(cartExample);

        // 找到了修改数量；没找到插入一条新数据
        if (marketCarts.size() != 0) {
            MarketCart marketCart2 = new MarketCart();
            marketCart2.setId(marketCarts.get(0).getId());
            marketCart2.setNumber((short) (marketCarts.get(0).getNumber() + marketCart.getNumber()));
            marketCartMapper.updateByPrimaryKeySelective(marketCart2);

            Integer count = marketCartMapper.goodsCount(userId);

            return count;
        }

        marketCart.setUserId(userId);

        marketCart.setDeleted(false);

        // marketGoods
        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(marketCart.getGoodsId());
        marketCart.setGoodsSn(marketGoods.getGoodsSn());
        marketCart.setGoodsName(marketGoods.getName());

        // marketGoodsProduct
        MarketGoodsProduct marketGoodsProduct = marketGoodsProductMapper.selectByPrimaryKey(marketCart.getProductId());
        marketCart.setPrice(marketGoods.getRetailPrice());
        marketCart.setSpecifications(marketGoodsProduct.getSpecifications());
        marketCart.setChecked(true);
        marketCart.setPicUrl(marketGoods.getPicUrl());
        marketCart.setAddTime(new Date());

        marketCartMapper.insert(marketCart);

        Integer count = marketCartMapper.goodsCount(userId);

        return count;
    }

    @Override
    public void update(MarketCart marketCart) {
        // marketCart 中封装了 cart_id 可以根据 cart_id 直接修改
        MarketCartExample example = new MarketCartExample();
        MarketCartExample.Criteria criteria = example.createCriteria();
        criteria.andDeletedEqualTo(false);
        criteria.andIdEqualTo(marketCart.getId());

        MarketCart marketCart2 = new MarketCart();
        marketCart2.setNumber(marketCart.getNumber());
        marketCart2.setUpdateTime(new Date());

        marketCartMapper.updateByExampleSelective(marketCart2, example);
    }

    @Override
    public CartData delete(Integer[] productIds) {
        // 获取用户 id
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection principals = subject.getPrincipals();

        // 未登录
        if (principals == null) {
            return null;
        }
        MarketUser primaryPrincipal = (MarketUser) principals.getPrimaryPrincipal();
        Integer userId = primaryPrincipal.getId();


        // 删除选中的 productIds
        MarketCartExample example = new MarketCartExample();
        MarketCartExample.Criteria criteria = example.createCriteria();
        criteria.andProductIdIn(Arrays.asList(productIds));
        criteria.andUserIdEqualTo(userId);

        MarketCart marketCart = new MarketCart();
        marketCart.setDeleted(true);
        marketCart.setUpdateTime(new Date());

        marketCartMapper.updateByExampleSelective(marketCart, example);

        // 回显
        MarketCartExample cartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria2 = cartExample.createCriteria();
        criteria2.andDeletedEqualTo(false);
        criteria2.andUserIdEqualTo(userId);
        List<MarketCart> cartList = marketCartMapper.selectByExample(cartExample);

        // goodsCount
        CartTotal cartTotal = getCartTotal(userId);

        CartData cartData = new CartData();
        cartData.setCartList(cartList);
        cartData.setCartTotal(cartTotal);

        return cartData;
    }

    @Override
    public CheckOutData checkout(CheckedOutParam checkedOutParam) {
        // 获取用户 id
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection principals = subject.getPrincipals();

        // 未登录
        if (principals == null) {
            return null;
        }
        MarketUser primaryPrincipal = (MarketUser) principals.getPrimaryPrincipal();
        Integer userId = primaryPrincipal.getId();


        CheckOutData checkOutData = new CheckOutData();
        checkOutData.data(checkedOutParam);

        // orderTotalPrice
        Double checkedGoodsAmount = null;
        if (checkedOutParam.getCartId() == 0) {
            checkedGoodsAmount = marketCartMapper.checkedGoodsAmount(userId);
            checkOutData.setOrderTotalPrice(BigDecimal.valueOf(checkedGoodsAmount));
        } else {
            checkedGoodsAmount = marketCartMapper.fastAddGoodsAmount(checkedOutParam.getCartId());
            checkOutData.setOrderTotalPrice(BigDecimal.valueOf(checkedGoodsAmount));
        }


        // goodsTotalPrice
        checkOutData.setGoodsTotalPrice(BigDecimal.valueOf(checkedGoodsAmount));

        // address
        MarketAddress marketAddress = marketAddressMapper.selectByPrimaryKey(checkOutData.getAddressId());
        checkOutData.setCheckedAddress(marketAddress);

        // 查询运费信息
        ArrayList<String> list = new ArrayList<>();
        list.add("market_express_freight_min");
        list.add("market_express_freight_value");

        HashMap<String, String> map = new HashMap<>();
        for (String keyName : list) {
            MarketSystemExample example = new MarketSystemExample();
            MarketSystemExample.Criteria criteria = example.createCriteria();
            criteria.andKeyNameEqualTo(keyName);

            List<MarketSystem> marketSystems = marketSystemMapper.selectByExample(example);

            map.put(keyName, marketSystems.get(0).getKeyValue());
        }
        if (checkOutData.getOrderTotalPrice().compareTo(BigDecimal.valueOf(Double.parseDouble(map.get("market_express_freight_min")))) >= 0) {
            checkOutData.setFreightPrice(BigDecimal.valueOf(0));
        } else {
            checkOutData.setFreightPrice(BigDecimal.valueOf(Double.parseDouble(map.get("market_express_freight_value"))));
        }

        // checkedGoodsList
        MarketCartExample checkedExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = checkedExample.createCriteria();
        criteria.andDeletedEqualTo(false).andCheckedEqualTo(true).andUserIdEqualTo(userId);
        if (checkOutData.getCartId() != 0) {
            criteria.andIdEqualTo(checkedOutParam.getCartId());
        }

        List<MarketCart> checkedCartList = marketCartMapper.selectByExample(checkedExample);
        checkOutData.setCheckedGoodsList(checkedCartList);

        // couponPrice
        MarketCouponUser marketCouponUser = marketCouponUserMapper.selectByPrimaryKey(checkedOutParam.getUserCouponId());

        MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(marketCouponUser == null ? 0 : marketCouponUser.getCouponId());
        checkOutData.setCouponPrice(marketCoupon == null ? BigDecimal.valueOf(0) : marketCoupon.getDiscount());

        // availableCouponLength
        if (marketCouponUser == null) {
            checkOutData.setAvailableCouponLength(0);
        } else {
            Date endTime = marketCouponUser.getEndTime();
            checkOutData.setAvailableCouponLength((int) ((endTime.getTime() - new Date().getTime()) / (1000 * 3600 * 24)));
        }

        // grouponPrice
        MarketGrouponRules marketGrouponRules = marketGrouponRulesMapper.selectByPrimaryKey(checkOutData.getGrouponRulesId());
        checkOutData.setGrouponPrice(marketGrouponRules == null ? BigDecimal.valueOf(0) : marketGrouponRules.getDiscount());

        // actualPrice
        checkOutData.setActualPrice(
                checkOutData.getOrderTotalPrice().subtract(
                        checkOutData.getCouponPrice()).subtract(
                        checkOutData.getGrouponPrice()).add(
                        checkOutData.getFreightPrice()));

        return checkOutData;
    }

    @Override
    public Integer goodscount() {
        // 获取用户 id
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection principals = subject.getPrincipals();

        // 未登录
        if (principals == null) {
            return -1;
        }
        MarketUser primaryPrincipal = (MarketUser) principals.getPrimaryPrincipal();
        Integer userId = primaryPrincipal.getId();

        MarketCartExample example = new MarketCartExample();
        MarketCartExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId);

        Integer count = marketCartMapper.goodsCount(userId);

        return count == null ? 0 : count;
    }

    @Override
    public Integer fastadd(MarketCart marketCart) {
        // 获取用户 id
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection principals = subject.getPrincipals();

        // 未登录
        if (principals == null) {
            return -1;
        }
        MarketUser primaryPrincipal = (MarketUser) principals.getPrimaryPrincipal();
        Integer userId = primaryPrincipal.getId();

        // 查询购物车中有没有该商品
        MarketCartExample cartExample = new MarketCartExample();
        cartExample.createCriteria().andDeletedEqualTo(false).andGoodsIdEqualTo(marketCart.getGoodsId()).andUserIdEqualTo(userId);

        List<MarketCart> marketCarts = marketCartMapper.selectByExample(cartExample);

        // 找到了修改数量；没找到插入一条新数据
        if (marketCarts.size() != 0) {
            MarketCart marketCart2 = new MarketCart();
            marketCart2.setId(marketCarts.get(0).getId());
            marketCart2.setNumber(marketCart.getNumber());
            marketCart2.setGoodsId(marketCart.getGoodsId());
            marketCart2.setProductId(marketCart.getProductId());
            marketCartMapper.updateByPrimaryKeySelective(marketCart2);

            return marketCarts.get(0).getId();
        }


        marketCart.setDeleted(false);

        // marketGoods
        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(marketCart.getGoodsId());
        marketCart.setGoodsSn(marketGoods.getGoodsSn());
        marketCart.setGoodsName(marketGoods.getName());

        // marketGoodsProduct
        MarketGoodsProduct marketGoodsProduct = marketGoodsProductMapper.selectByPrimaryKey(marketCart.getProductId());
        marketCart.setPrice(marketGoods.getRetailPrice());
        marketCart.setSpecifications(marketGoodsProduct.getSpecifications());
        marketCart.setChecked(true);
        marketCart.setPicUrl(marketGoods.getPicUrl());
        marketCart.setAddTime(new Date());
        marketCart.setUserId(userId);

        marketCartMapper.insert(marketCart);

        return marketCart.getId();
    }
}
